package com.edu.whty.controller;

import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.*;
import com.edu.whty.entity.base.AttachFile;
import com.edu.whty.entity.base.Pagination;
import com.edu.whty.entity.base.SpecialRepo;
import com.edu.whty.entity.disk.DiskOwner;
import com.edu.whty.entity.disk.ResOwner;
import com.edu.whty.entity.school.*;
import com.edu.whty.service.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TODO
 *
 * @author luyao
 * @explain
 * @date 2021/5/5
 */
@Controller
public class SchoolController {

    private Logger LOGGER = LogManager.getLogger(SchoolController.class);


    @Autowired
    private DiskService diskService;
    @Autowired
    private SpecialResourceCatalogService specialResourceCatalogService;


    @Autowired
    private SchoolResourceService schoolResourceService;

    @Autowired
    private SpecialRepoService specialRepoService;

    @Autowired
    private AttachFileService attachFileService;

    @Value("${rrtbk.streamUrl}")
    private String streamUrl;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;


    @RequestMapping(value = "/SpecialRepoNoBM/{orgId}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getFolder(@PathVariable String orgId, String noBM) throws Exception{
        Map<String, Object> result=new HashMap<>();
        if(StringUtils.isBlank(orgId)){
            result.put("result", "100000");
            result.put("resultDesc","orgId不能为空");
            return result;
        }


        List<SpecialRepo>list =  specialRepoService.getSpecialRepoList(null);
        result.put("result", "000000");
        result.put("resultDesc","success");
        result.put("count", list.size());
        result.put("data", list);
        return result;
    }


    private void  getCatalogList(JSONArray jsonArray ,SpecialResourcesBase repo){
        //2.获取该专题的目录列表
        SpecialResourceCatalog param = new SpecialResourceCatalog();
        param.setTSpecialResourcesId(repo.getId());
        param.setStatus(0);
        List<SpecialResourceCatalog> catalogList = specialResourceCatalogService.selectListByModel(param);
        getInitNodeInfoData(jsonArray,"0",catalogList, repo);
    }

    void getInitNodeInfoData(JSONArray jsonArray ,String parentId,List<SpecialResourceCatalog> catalogList,SpecialResourcesBase repo){
        if(catalogList !=null && catalogList.size()>0){
            for (int i=0;i<catalogList.size();i++){
                SpecialResourceCatalog catalog = catalogList.get(i);
                if(parentId.equals(catalog.getParentId())){
                    JSONObject jsonData = new JSONObject();
                    jsonData.put("id", catalog.getCatalogId());
                    if("0".equals(catalog.getParentId())){
                        jsonData.put("pId", repo.getId());
                    }else {
                        jsonData.put("pId", catalog.getParentId());
                    }
                    jsonData.put("repoId",repo.getId());
                    jsonData.put("name", catalog.getCatalogName());
                    jsonData.put("isCatalog", 0);
                    jsonArray.add(jsonData);
                    getInitNodeInfoData(jsonArray, catalog.getCatalogId(),catalogList,repo);
                }
            }
        }
    }

    /**
     * 根据目录查询专题资源的接口
     *
     * @return ResponseMessage
     * @throws Exception
     * @author 施路遥
     * @date 2020年11月10日
     */
    @RequestMapping(value = "/getRepoResourceListByCatalog", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getRepoResourceListByCatalog( @RequestBody JSONObject obj) throws Exception{
        Map<String, Object> result=new HashMap<>();
        ProdOwner prodOwner = new ProdOwner();
        //1.获取专题信息
        Pagination pagination = new Pagination();
        if (null == obj.get("curPage")) {
            result.put("result", "100000");
            result.put("resultDesc","curPage不能为空");
            return result;
        }
        if (null == obj.get("pageSize")) {
            result.put("result", "100000");
            result.put("resultDesc","numPerPage不能为空");
            return result;
        }
        Integer curPage = obj.getInt("curPage");
        Integer numPerPage = obj.getInt("pageSize");
        pagination.setNumPerPage(numPerPage);
        pagination.setCurPage(curPage);

        if (null == obj.get("isCatalog")) {
            result.put("result", "100000");
            result.put("resultDesc","isCatalog不能为空");
            return result;
        }
        if (null == obj.get("repoId")) {
            result.put("result", "100000");
            result.put("resultDesc","repoId不能为空");
            return result;
        }
        String auditStatus = obj.optString("auditStatus");
        String isCatalog = obj.optString("isCatalog");
        String repoId = obj.optString("repoId");
        String catalogId = obj.optString("catalogId");
        String keyword = obj.optString("keyword");
        String format = obj.optString("format");
        String orderby = obj.optString("orderby"); //时间倒序
        if("0".equals(isCatalog) ) {//为0时是查询的是普通专题资源库(根据文件夹查询),为1是带编目专题资源库(根据章节目录查询)
//            RepoCatalogResource param = new RepoCatalogResource();
            if (!org.apache.commons.lang3.StringUtils.isEmpty(catalogId) ) {
                prodOwner.setChapterId(catalogId);
            }

            if (!org.apache.commons.lang3.StringUtils.isEmpty(auditStatus) ) {
                prodOwner.setAuditStatus(auditStatus);
            }

            if (!org.apache.commons.lang3.StringUtils.isEmpty(format) ) {
                prodOwner.setFormatId(format);
            }

            if (!org.apache.commons.lang3.StringUtils.isEmpty(orderby) ) {
                prodOwner.setOrderby(orderby);
            }

            prodOwner.setRepoId(repoId);
            if (!org.apache.commons.lang3.StringUtils.isEmpty(keyword) && !"null".equals(keyword)) {
                prodOwner.setProductName(keyword);
            }
            com.github.pagehelper.PageInfo pageInfo =schoolResourceService.queryForSchResPagination(pagination, prodOwner);
//            List<RepoCatalogResource> list = repoCatalogResourceService.selectAllResourceUnderRepoByPagination(param, pagination);
            List<ProdOwner> resList = new ArrayList<>();
            List<ProdOwner>  list = pageInfo.getList();

            for(ProdOwner prodOwner0:list){

                if("0".equals(prodOwner0.getUploadCos())){
                    AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(prodOwner0.getFId()));
                    if (attachFile != null && org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                        String downloadUrl = "";
                        if (attachFile.getFilePathRemote().contains("data1")) {
                            downloadUrl = streamUrl + attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                        } else {
                            downloadUrl = streamUrl + "/data1" + attachFile.getFilePathRemote();
                        }
                        prodOwner0.setDownloadUrl(downloadUrl);
                        if ("mp4".equals(attachFile.getFileExt().toLowerCase()) || Constant.picList.contains(prodOwner0.getFileExt().toLowerCase())) {
                            prodOwner0.setPreviewUrl(downloadUrl);

                        }
                    }else {
                        prodOwner0.setPreviewUrl("");
                        prodOwner0.setDownloadUrl("");
                    }
                }

                prodOwner0.setResId(prodOwner0.getResId());
                prodOwner0.setResName(prodOwner0.getResName());
                prodOwner0.setExt(prodOwner0.getFileExt());
                resList.add(prodOwner0);
            }
            result.put("data", resList);
            result.put("result", "000000");
            result.put("resultDesc", "success");
            result.put("curPage", pageInfo.getPageNum());
            result.put("pageSize", pageInfo.getPageSize());
            result.put("count", resList.size());
            result.put("totalPage", pageInfo.getTotal());
        }
        return result;
    }


    /**
     *
     * 查询章节下面的资源文件
     *
     */
    @RequestMapping(value = "/getResByChapterId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getResByChapterId(@RequestBody JSONObject obj) throws Exception{
        Map<String, Object> result=new HashMap<>();
        String chapterId=obj.optString("chapterId");
        String orgId=obj.optString("orgId");
        String classificationId=obj.optString("classificationId");
        if(StringUtils.isBlank(orgId)){
            result.put("result", "100000");
            result.put("resultDesc","orgId不能为空");
            return result;
        }
        ProdOwner prodOwner = new ProdOwner();
        if(StringUtils.isNotBlank(chapterId)){
            prodOwner.setChapterId(chapterId);
        }
        if(StringUtils.isNotBlank(classificationId)){
            prodOwner.setClassificationId(classificationId);
        }
        return queryForPagination(obj, result, orgId, prodOwner);
    }


    private Map<String, Object> queryForPagination(JSONObject obj, Map<String, Object> result, String orgId,
                                                   ProdOwner prodOwner) throws Exception {
        Pagination pagination = new Pagination();
        pagination.setCurPage(obj.optInt("curPage"));
        pagination.setNumPerPage(obj.optInt("pageSize"));
        String key = obj.optString("key");
        String userId = obj.optString("userId");
        String productName = obj.optString("productName");
        String auditStatus = obj.optString("auditStatus");
        String orderby = obj.optString("orderby");
        // 设置资源格式
        if ("1".equals(key)) {
            // 图片格式
            prodOwner.setFormatId("FMT02");
        } else if ("2".equals(key)) {
            // 文档格式
            prodOwner.setFormatId("FMT01");
        } else if ("3".equals(key)) {
            // 视频格式
            prodOwner.setFormatId("FMT04");
        } else if ("4".equals(key)) {
            // 音频格式
            prodOwner.setFormatId("FMT03");
        } else if ("5".equals(key)) {
            // 动画格式
            prodOwner.setFormatId("FMT05");
        } else if ("7".equals(key)) {
            // 查询互动类型时，数据库中没有这种资源格式，返回一个空列表(数据库表中无FMT100)
            prodOwner.setFormatId("FMT100");
        } else if("0".equals(key)){
            prodOwner.setFormatId("");    
        } else if (StringUtils.isNotEmpty(key)) {
            //兼容备课直接传formatId
            prodOwner.setFormatId(key);
        } else {
            prodOwner.setFormatId("");
        }
        // 设置排序条件
        if ("0".equals(orderby)) {
            prodOwner.setOrderby("SCORE DESC");
        } else if ("1".equals(orderby)) {
            prodOwner.setOrderby("COLLECTED_COUNT DESC");
        } else if ("2".equals(orderby)) {
            prodOwner.setOrderby("VIEW_COUNT DESC");
        } else if ("3".equals(orderby)) {
            prodOwner.setOrderby("FILE_LENGTH DESC");
        } else if ("4".equals(orderby)) {
            prodOwner.setOrderby("DOWN_COUNT DESC");
        } else if ("5".equals(orderby)) {
            prodOwner.setOrderby("CREATE_TIME DESC");
        }else {
            prodOwner.setOrderby("");
        }

        if (StringUtils.isNotBlank(productName)) {
            prodOwner.setProductName(productName);
        }

        if (StringUtils.isNotBlank(auditStatus)) {
            prodOwner.setAuditStatus(auditStatus);
        }

        prodOwner.setProvideOrgId(orgId);
        prodOwner.setCreatorId(userId);
        prodOwner.setIsFolder("1");
        //查询存在的数据
        prodOwner.setIsDelete("0");

        prodOwner.setParentId("");
        result=new HashMap<>();
        com.github.pagehelper.PageInfo pageInfo =schoolResourceService.queryForSchResPagination(pagination, prodOwner);
        int totalCount = (int) pageInfo.getTotal();
        List<ProdOwner> list = (List<ProdOwner>) pageInfo.getList();
        JSONArray jsonArray = new JSONArray();
        if (list != null) {
            Set<String> personSet = new HashSet<>();
            for (ProdOwner p : list) {
                if (StringUtils.isNotBlank(p.getCreatorId())) {
                    personSet.add(p.getCreatorId());
                } else {
                    personSet.add(null);
                }
            }

            JSONObject jsonObj;
            ResOwner resOwner;
            for (ProdOwner prod : list) {
                jsonObj = new JSONObject();
                resOwner = new ResOwner();
                resOwner.setResId(prod.getResId());
                // 获取预览地址
                String previewUrl = prod.getPreviewUrl();
                String downLoadUrl = prod.getDownloadUrl();
                jsonObj.put("resId", prod.getResId());
                jsonObj.put("productCode", prod.getProductCode());
                jsonObj.put("resName", prod.getProductName());
                jsonObj.put("ext", prod.getFileExt());
                jsonObj.put("fileLength", prod.getFileLength());
                jsonObj.put("fileSize", prod.getFileSize());

                if("1".equals(prod.getUploadCos())){
                    jsonObj.put("previewUrl",  previewUrl);
                    jsonObj.put("downUrl",  downLoadUrl);
                }else {
                    AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(prod.getFId()));
                    if (attachFile != null && org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                        String downloadUrl = "";
                        if (attachFile.getFilePathRemote().contains("data1")) {
                            downloadUrl = streamUrl + attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                        } else {
                            downloadUrl = streamUrl + "/data1" + attachFile.getFilePathRemote();
                        }
                        jsonObj.put("downUrl", downloadUrl);
                        if ("mp4".equals(attachFile.getFileExt().toLowerCase()) || Constant.picList.contains(prod.getFileExt().toLowerCase())) {
                            jsonObj.put("previewUrl", downloadUrl);

                        }
                    }
                }

                jsonObj.put("fid", prod.getFId());
                jsonObj.put("classificationId", prod.getClassificationId());
                jsonObj.put("creatorId", prod.getCreatorId());
                jsonObj.put("viewCount", prod.getViewCount() == null ? 0 : prod.getViewCount());
                jsonObj.put("downCount", prod.getDownCount() == null ? 0 : prod.getDownCount());
                jsonObj.put("collectCount", prod.getCollectedCount() == null ? 0 : prod.getCollectedCount());
                jsonObj.put("score", prod.getScore() == null ? 0 : prod.getScore());
                jsonObj.put("creatorName",prod.getCreatorName());
                jsonObj.put("createTime",prod.getCreateTime());
                jsonObj.put("auditStatus",prod.getAuditStatus());
                jsonObj.put("uploadCos", prod.getUploadCos());
                jsonArray.add(jsonObj);
            }
        }
        result.put("result", "000000");
        result.put("resultDesc", "success");
        result.put("curPage", pagination.getCurPage());
        result.put("pageSize", pagination.getNumPerPage());
        result.put("totalPage", totalCount % 10 > 0 ? totalCount / 10 + 1 : totalCount / 10);
        result.put("count", totalCount);
        result.put("data", jsonArray);
        return result;
    }

    /**
     * 获取资源详情接口
     *
     * @param resId
     * @return
     * @throws Exception
     * @author xiongxf
     * @date 2014年9月5日
     */
    @RequestMapping(value = "/productDetail/{resId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage resourceDetail(@PathVariable String resId) throws Exception {

        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (org.apache.commons.lang.StringUtils.isBlank(resId)) {
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("参数resId不能为空");
            return responseMessage;
        }
        ProdOwner prodOwner = schoolResourceService.getProdOwner(resId);

        if (prodOwner == null) {
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("资源不存在");
            return responseMessage;
        }

        if(prodOwner.getViewCount() == null){
            prodOwner.setViewCount(0L);
        }
        prodOwner.setViewCount(prodOwner.getViewCount()+1);
        schoolResourceService.updateViewCount(prodOwner);
        getDownloadPlayUrl(prodOwner);
        responseMessage.setData(prodOwner);
        return responseMessage;
    }

    @RequestMapping(value = "/openResource/{productCode}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage openResource(@PathVariable String productCode) throws Exception{
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (org.apache.commons.lang.StringUtils.isBlank(productCode)) {
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("参数productCode不能为空");
            return responseMessage;
        }

        ProdOwner prodOwner =  schoolResourceService.getProdOwner(productCode);
        if(prodOwner == null) {
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("资源不存在");
            return responseMessage;
        }
        prodOwner.setOpenCount(prodOwner.getOpenCount() == null?0:prodOwner.getOpenCount() +1);
        schoolResourceService.updateOpenCount(prodOwner);
        return responseMessage;
    }

    private void getDownloadPlayUrl(ProdOwner prodOwner) throws Exception{
        prodOwner.setPlayUrl("");
        if("1".equals(prodOwner.getUploadCos())){
            prodOwner.setPlayUrl(prodOwner.getPreviewUrl());
        }else {
            AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(prodOwner.getFId()));
            if(attachFile != null&&StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                String downloadUrl = "";
                if(attachFile.getFilePathRemote().contains("data1")&&StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                    downloadUrl = streamUrl+attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                }else {
                    downloadUrl = streamUrl+"/data1"+attachFile.getFilePathRemote();
                }
                prodOwner.setDownloadUrl(downloadUrl);
                if (Constant.picList.contains(attachFile.getFileExt().toLowerCase()) || Constant.videoList.contains((attachFile.getFileExt().toLowerCase()))) {
                    prodOwner.setPreviewUrl(prodOwner.getDownloadUrl());
                }
            }
        }
    }


    /**
     * 用户的教材权限
     *
     * @param schoolId 学校id
     * @param userId   用户id
     * @return 用户的教材权限列表
     */
    @RequestMapping(value = "getUserSchTextbookPriv/{schoolId}/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getUserSchTextbookPriv(@PathVariable("schoolId") String schoolId,
                                                  @PathVariable("userId") String userId) {
        ResponseMessage responseMessage = new ResponseMessage();
        LOGGER.info("getUserSchTextbookPriv.schoolId = {},--userId = {}", schoolId, userId);
        //判断一下 学校是否设置该权限
        ResAttrValueDto attrValueDto = new ResAttrValueDto();
        attrValueDto.setAttrInnerCode("SCHOOL_" + schoolId);
        attrValueDto.setSpecStatus("0");
        ResAttrValue value = schoolResourceService.getSchTextbookPrivSwitch(attrValueDto);
        if (value == null) {
            responseMessage.setData(null);
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("未初始化过该学校[" + schoolId + "]教材权限");
            return responseMessage;
        }
        LOGGER.info("queryTextbookPrivByUser.schoolId = {},--userId = {}", schoolId, userId);
        List<BaseTextbookDto> list = schoolResourceService.queryTextbookPrivByUser(schoolId, userId);
        if(!CollectionUtils.isEmpty(list)){
            for(BaseTextbookDto dto : list){
                String periodName = dto.getPeriodName();
                String textbookName = dto.getTextbookName();
                if(StringUtils.isNotBlank(textbookName) && textbookName.startsWith(periodName) ){
                    textbookName = StringUtils.removeStart(textbookName,periodName);
                }
                dto.setTextbookName(textbookName);
            }
        }
        // 返回翻译字段
        responseMessage.setData(list);
        responseMessage.setResult("000000");
        responseMessage.setResultDesc("查詢成功");
        return responseMessage;
    }



    /**
     * 查询当前用户的专题目录权限
     *
     * @param dto 入参
     * @return 返回
     */
    @RequestMapping(value = "getUserCatalogPriv", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getUserCatalogPriv(@RequestBody TextbookQryDto dto) {
        ResponseMessage message = new ResponseMessage();
        LOGGER.info("getUserCatalogPriv.param = {}", dto);

        //判断一下 学校是否设置该权限
        ResAttrValueDto attrValueDto = new ResAttrValueDto();
        attrValueDto.setAttrInnerCode("SCHOOL_" + dto.getOrgId());
        attrValueDto.setSpecStatus("0");
        ResAttrValue value = schoolResourceService.getSchTextbookPrivSwitch(attrValueDto);
        if (value == null) {
            message.setData(null);
            message.setResult("100000");
            message.setResultDesc("未初始化过该学校[" + dto.getOrgId() + "]教材权限");
            return message;
        }

        Map<String, Object> mapParam = new HashMap<String, Object>();
        mapParam.put("resourcesType", 0);
        mapParam.put("isDelete", "0");
        mapParam.put("isShow", "1");
        mapParam.put("orgId", dto.getOrgId());
        JSONArray objects = specialRepoService.queryCatalogTreeByUser(mapParam, dto);
        message.setData(objects);
        message.setResult("000000");
        message.setResultDesc("查询专题目录树成功");
        return message;
    }


    /**
     * 校本资源上传保存
     * @param
     * @param prodOwner
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadResource")
    @ResponseBody
    public ResponseMessage uploadResource(@RequestBody ProdOwner prodOwner) throws Exception{

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ResponseMessage message =  ResponseMessage.getSuccessResponse();
        DiskOwner diskOwner = new DiskOwner();
        prodOwner.setResId(UUIDUtils.getRandomUUID());
        prodOwner.setProductCode("PD" + SnowflakeUtils.getNextId());
        prodOwner.setCreateTime(sdf.format(new Date()));
        schoolResourceService.saveSchoolRes(prodOwner);
        BeanUtils.copyProperties(prodOwner,diskOwner);
        if(StringUtils.isBlank(prodOwner.getRepoId())){
            diskOwner.setDirId(UUIDUtils.getRandomUUID());
            diskOwner.setDirName(prodOwner.getProductName());
            diskService.insert(diskOwner);
        }
        message.setData(prodOwner);
        return message;

    }


    /**
     * 校本资源取消分享
     * @param
     * @param prodOwner
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cancelShare")
    @ResponseBody
    public ResponseMessage cancelShare(@RequestBody ProdOwner prodOwner){
        ResponseMessage message =  ResponseMessage.getSuccessResponse();
        schoolResourceService.deleteSchoolRes(prodOwner);
        message.setData(prodOwner.getProductCode());
        return message;

    }


    /**
     * 资源审核
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/auditResource")
    @ResponseBody
    public ResponseMessage auditResource(@RequestBody ProdOwner prodOwner){
        ResponseMessage message =  ResponseMessage.getSuccessResponse();

        if (org.apache.commons.lang.StringUtils.isBlank(prodOwner.getResId())) {
            message = ResponseMessage.getFailedResponse();
            message.setResultDesc("参数resId不能为空");
            return message;
        }
        schoolResourceService.auditResource(prodOwner);
        message.setResultDesc("审核完成");
        return message;

    }


    /**
     * 资源审核
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateResource")
    @ResponseBody
    public ResponseMessage updateResource(@RequestBody ProdOwner prodOwner){
        ResponseMessage message =  ResponseMessage.getSuccessResponse();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (org.apache.commons.lang.StringUtils.isBlank(prodOwner.getResId())) {
            message = ResponseMessage.getFailedResponse();
            message.setResultDesc("参数resId不能为空");
            return message;
        }
        prodOwner.setModifyTime(sdf.format(new Date()));
        schoolResourceService.updateResource(prodOwner);
        message.setResultDesc("更新成功");
        return message;

    }


    /**
     * 资源审核
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadDisk")
    @ResponseBody
    public ResponseMessage uploadDisk(@RequestBody AttachFile attachFile) throws Exception{
        ResponseMessage message =  ResponseMessage.getSuccessResponse();
        JSONObject json = new JSONObject();
        Long fid = 0L;
        URL fileUrl = new URL(streamUrl+"/data1"+attachFile.getFilePathLocal());

        HttpURLConnection urlConnection = (HttpURLConnection) fileUrl.openConnection();
        Long fileLength = urlConnection.getContentLengthLong();
        InputStream is = urlConnection.getInputStream();
        String fileMd5= DigestUtils.md5Hex(is);
        String fileExt = FileUtil.getFileType(attachFile.getFilePathLocal());

        attachFile.setFid(SnowflakeUtils.getNextId());
        attachFile.setFileLength(fileLength);
        attachFile.setFileMd5(fileMd5);
        attachFile.setFilePos(fileLength);
        attachFile.setFileSize(FileUtils.size2string(fileLength));
        attachFile.setFileExt(fileExt);
        attachFile.setIsDeleted("false");
        attachFile.setPostComplete("true");
        attachFile.setPostedTime(new Date());
        attachFile.setPostedLength(fileLength);
        attachFile.setPostedPercent("100%");
        attachFile.setIsLocal("1");
        fid = attachFileService.addAttachFile(attachFile);
        json.put("fid",fid);

        DiskOwner diskOwner = new DiskOwner();
        diskOwner.setDirId(UUIDUtils.getRandomUUID());
        diskOwner.setTitle(attachFile.getFileNameLocal());
        diskOwner.setResForm("3");//ftp直接上传的附件
        diskOwner.setFid(String.valueOf(fid));
        diskOwner.setFileSize(attachFile.getFileSize());
        diskOwner.setFileExt(fileExt);
        diskOwner.setFileLength(fileLength);
        diskOwner.setDirName(attachFile.getFileNameLocal());
        diskOwner.setUserId(attachFile.getUserId());
        diskOwner.setCreateTime(DateUtils.getCurDateTime());
        diskService.insert(diskOwner);
        json.put("dirId",diskOwner.getDirId());
        message.setData(json);
        return message;

    }
}
